package com.zut.blocks.service.grade.impl;

import com.zut.blocks.base.common.request.CourseGradeRequest;
import com.zut.blocks.base.domain.CourseGrade;
import com.zut.blocks.base.service.impl.GenericServiceImpl;
import com.zut.blocks.dao.course.CourseRepository;
import com.zut.blocks.dao.course.grade.CourseGradeRepository;
import com.zut.blocks.service.grade.CourseGradeService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author lxd
 * @date 2020/12/1 22:34
 */
@Service
public class CourseGradeServiceImpl extends GenericServiceImpl<CourseGrade, Integer> implements CourseGradeService {

    @Resource
    CourseGradeRepository courseGradeRepository;

    @Resource
    CourseRepository courseRepository;

    @Override
    public Page<CourseGrade> findAll(CourseGradeRequest request) {
        return courseGradeRepository.findAll(request.example(), request.pageable(true));
    }

    @Override
    public List<CourseGrade> getByCourseId(Integer courseId) {
        Assert.notNull(courseId, "course id 不能为空");
//        Optional<Course> optionalCourse = courseRepository.findById(courseId);
//        Assert.isTrue(optionalCourse.isPresent(), "课程不存在: course id: " + courseId);

        CourseGrade cg = new CourseGrade();
        cg.setCourseId(courseId);
        return courseGradeRepository.findAll(
                Example.of(cg, ExampleMatcher
                        .matching()
                        .withMatcher("courseId", ExampleMatcher.GenericPropertyMatchers.exact())));
    }

    @Override
    public CourseGrade save(CourseGrade courseGrade) {
        // check
        Assert.notNull(courseGrade, "course grade 不能为空");

        courseGrade.setId(null);
        courseGrade.setCreateTime(new Date());
        return courseGradeRepository.save(courseGrade);
    }

    @Override
    public Integer delete(Integer courseGradeId) {
        Assert.notNull(courseGradeId, "course grade id 不能为空");
        courseGradeRepository.deleteById(courseGradeId);
        return courseGradeId;
    }

    @Override
    public List<CourseGrade> findAllByCourseId(Integer courseId) {
        Assert.notNull(courseId, "course id 不能为空");
        return courseGradeRepository.findAllByCourseId(courseId);
    }

    @Override
    public Integer add(CourseGrade courseGrade) {
        courseGradeRepository.save(courseGrade);
        return courseGrade.getId();
    }


}
